﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Expression.Interactivity.Core;
using YFIN.View.Controls;
using YFIN.View.User;
using YFIN.View.Helper;
using YFIN.View.ReminderServiceRef;
using System.Collections.ObjectModel;
using YFIN.View.Lockbox;
using YFIN.View.MessageServiceRef;
using System.Threading;
using System.Diagnostics;


namespace YFIN.View.ViewModels
{
    public class LoginVM : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion

        #region 属性
        /// <summary>
        /// 用户名
        /// </summary>
        private string _userName;
        public string UserName
        {
            get
            {
                return _userName;
            }
            set
            {
                if (_userName != value)
                {
                    _userName = value;
                    NotifyPropertyChanged("UserName");
                }
            }
        }

        /// <summary>
        /// 密码
        /// </summary>
        private string _password;
        public string Password
        {
            get
            {
                return _password;
            }
            set
            {
                if (_password != value)
                {
                    _password = value;
                    NotifyPropertyChanged("Password");
                }
            }
        }
        /// <summary>
        /// 密码
        /// </summary>
        public Login login { get; set; }

        /// <summary>
        /// 验证码
        /// </summary>
        private WriteableBitmap _code;
        public WriteableBitmap Code
        {
            get
            {
                return _code;
            }
            set
            {
                if (_code != value)
                {
                    _code = value;
                    NotifyPropertyChanged("Code");
                }
            }
        }

        /// <summary>
        /// 输入的验证码
        /// </summary>
        private string _codeStr;
        public string CodeStr
        {
            get
            {
                return _codeStr;
            }
            set
            {
                if (_codeStr != value)
                {
                    _codeStr = value;
                    NotifyPropertyChanged("CodeStr");
                }
            }
        }
        /// <summary>
        /// 绑定到的实现登录操作的命令
        /// </summary>
        /// 
        public ICommand LoginCommand { get; private set; }
        public ICommand ChangeCodeCommand { get; private set; }
        #endregion

        private string _codeStrTrue;
        public LoginVM()
        {
            LoginCommand = new ActionCommand(Login);
            ChangeCodeCommand = new ActionCommand(ChangeCode);
            var c = VerifyCode.GetVerifyCode();
            Code = c.Value;
            _codeStrTrue = c.Key;
        }

        public void ChangeCode()
        {
            var c = VerifyCode.GetVerifyCode();
            Code = c.Value;
            _codeStrTrue = c.Key;
        }

        public void Login()
        {
            login.UserBox.ClearValidationError();
            login.PasswordBox.ClearValidationError();
            bool isValid = true;
            if (login.UserBox.Text.Length == 0)
            {
                login.UserBox.ShowValidationError("用户名不能为空");
                isValid = false;
                ChangeCode();
            }
            if (login.PasswordBox.Password.Length <= 5)
            {
                login.PasswordBox.ShowValidationError("密码必须大于等于6位");
                isValid = false;
                ChangeCode();
            }
            if (CodeStr != _codeStrTrue)
            {
                login.tb.ShowValidationError("验证码不正确");
                isValid = false;
                ChangeCode();
            }
            if (isValid)
            {
                var client = new UserServiceRef.UserServiceClient();
                client.ExistCompleted += client_ExistCompleted;
                client.ExistAsync(UserName, login.PasswordBox.Password.GetHashCode().ToString());
            }
        }

        private void client_ExistCompleted(object sender, UserServiceRef.ExistCompletedEventArgs e)
        {
            if (e.Result == null)
            {
                MessageBox.Show("用户名或密码错误！");
                ChangeCode();
                //TODO
            }
            else
            {
                var client = new ReminderServiceClient();
                client.GetByUserNameCompleted += new EventHandler<GetByUserNameCompletedEventArgs>(client_GetByUserNameCompleted);
                client.GetByUserNameAsync(UserName);
                Stage.Login(e.Result);

                Stage.TheLogin.Close();
            }
        }

        ObservableCollection<Timer> _timers = new ObservableCollection<Timer>();
        private void client_GetByUserNameCompleted(object sender, GetByUserNameCompletedEventArgs e)
        {
            var now = DateTime.Now;
            var rTimer = e.Result.Where(rs => rs.Time > now);
            var rNow = e.Result.Where(rs => rs.Time <= now && rs.IsEnabled);
            foreach (var r in rNow)
            {
                var client = new MessageServiceClient();
                client.AddCompleted += new EventHandler<MessageServiceRef.AddCompletedEventArgs>(client_AddCompleted);
                client.AddAsync(new ModelMessage
                {
                    Time = now,
                    Content = r.Content ?? "",
                    Sender = "#YFIN#",
                    Receiver = UserName,
                    IsNew = true,
                    Repliable = false,
                    Priority = 3,
                    Title = "系统消息",
                });

                r.IsEnabled = false;
                var Rclient = new ReminderServiceClient();
                Rclient.UpdateCompleted += new EventHandler<ReminderServiceRef.UpdateCompletedEventArgs>(Rclient_UpdateCompleted);
                Rclient.UpdateAsync(r);
                Stage.SetNewMsg();
            }

            foreach (var r in rTimer)
            {
                _timers.Add(new Timer(new TimerCallback(executeRun), r, (int)((r.Time - DateTime.Now).TotalMilliseconds), 0));
               
            }
        }

        private void executeRun(object obj)
        {
            var r = (ModelReminder)obj;
            var client = new MessageServiceClient();
            client.AddCompleted += new EventHandler<MessageServiceRef.AddCompletedEventArgs>(client_AddCompleted1);
            client.AddAsync(new ModelMessage
            {
                Time = DateTime.Now,
                Content = r.Content ?? "",
                Sender = "#YFIN#",
                Receiver = UserName,
                IsNew = true,
                Repliable = false,
                Priority = 3,
                Title = "系统消息",
            });
            r.IsEnabled = false;
            var Rclient = new ReminderServiceClient();
            Rclient.UpdateCompleted += new EventHandler<ReminderServiceRef.UpdateCompletedEventArgs>(Rclient_UpdateCompleted);
            Rclient.UpdateAsync(r);
        }

        private void client_AddCompleted(object sender, MessageServiceRef.AddCompletedEventArgs e)
        {
            if (e.Result)
            {
                var client = new MessageServiceClient();
                client.GetByReceiverCompleted += new EventHandler<GetByReceiverCompletedEventArgs>(client_GetByReceiverCompleted);
                client.GetByReceiverAsync(Stage.User.UserName);
            }
        }

        private void client_AddCompleted1(object sender, MessageServiceRef.AddCompletedEventArgs e)
        {
            if (e.Result)
            {
            }
        }

        private void client_GetByReceiverCompleted(object sender, GetByReceiverCompletedEventArgs e)
        {
            Message.Mvm.Messages = e.Result;
        }

        private void Rclient_UpdateCompleted(object sender, ReminderServiceRef.UpdateCompletedEventArgs e)
        {
            if (e.Result)
            {
            }
        }
    }
}
